<template>
  <div class="update">
    <overlay v-if="this.showMaskLayer" />
    <issue-component
      v-else
      :orderInformation="orderInformation"
    >
      <div slot="button" class="myButton">
        <van-button round type="info" @click="updateHandler" slot="button">
          {{ $t("orders.button.modifyOrder") }}
        </van-button>
        <van-button round type="danger" @click="cancelHandler" slot="button">
          {{ $t("orders.button.undoOrder") }}
        </van-button>
      </div>
    </issue-component>
  </div>
</template>

<script>
import issueComponent from 'components/content/order/issue-order/issue-order.vue';
import { mapState, mapMutations } from 'vuex';
import { Button } from 'vant';
import overlay from 'components/content/overlay/overlay.vue';

export default {
    name: 'update-orderInfo',
    components: {
        issueComponent,
        overlay,
        [Button.name]: Button
    },
    data () {
        return {
            orderInformation: {}, // 订单信息
            orderId: '' // 订单的ID
        };
    },
    created () {
        this.orderId = this.$route.params.orderId; // 尝试获取当前路由的订单ID
        // 如果vuex内存放有就取vuex内的数据
        if (JSON.stringify(this.tempIssueOrderInfo) !== '{}') {
            this.orderInformation = this.tempIssueOrderInfo;
            this.pushImage(this.orderInformation.orderPicture);
            this.simpleAssignment({ state: 'tempIssueOrderInfo', value: {} });
        } else {
            this.requestOrder();
        }
    },
    computed: {
        ...mapState([
            'tempIssueOrderInfo',
            'tempOrderPicture',
            'watchPictureModify',
            'showMaskLayer'
        ])
    },
    methods: {
    // 更新订单
        updateHandler () {
            const isEmpty = _.some(this.orderInformation, item => item === '' || (Array.isArray(item) && item.length === 0));
            if (isEmpty) {
                // 订单含有空的信息，禁止更新订单
                this.$util.failToast(this.$t('orders.mustHaveAll'));
            } else {
                this.$util.loadingToast();
                this.$api.orderApi.detail(this.orderInformation._id).then(({ data: { isOrderTaked } }) => {
                    if (isOrderTaked) {
                        // 该跑腿已经被接单，无法继续更新信息
                        this.$util.failToast(this.$t('orders.updateFailure'));
                    } else {
                        const userPhone = { userPhone: this.$store.state.userInfo.telephone };
                        // 将json数据转换成form-data
                        const formData = this.$util.jsonTransformData(Object.assign(this.orderInformation, userPhone));
                        this.$api.orderApi.updateOrder(formData)
                            .then(result => {
                                this.$util.successToast(result.message);
                            })
                            .catch(error => {
                                this.$util.failToast(error.message);
                            });
                    }
                });
            }
        },
        // 取消跑腿订单
        cancelHandler () {
            this.$dialog
                .confirm({ message: this.$t('orders.sureCancel') })
                .then(() => {
                    this.$api.messageApi.delete({ orderId: this.orderInformation._id })
                        .then(() => {
                            this.$api.orderApi
                                .delete({ id: this.orderInformation._id })
                                .then(() => {
                                    this.$router.replace({ name: 'orders' });
                                })
                                .catch(err => {
                                    throw err;
                                });
                        })
                        .catch(error => {
                            this.$util.failToast(error);
                        });
                })
                .catch(() => {});
        },
        pushImage (data) {
            const tempArray = [];
            for (const index in data) {
                if (typeof data[index] === 'object') {
                    // 用户新增的图片
                    tempArray.push(data[index]);
                } else {
                    // string类型的url地址
                    tempArray.push({ url: data[index] });
                }
            }
            this.$set(this.orderInformation, 'orderPicture', tempArray);
        },
        // 请求订单信息
        requestOrder () {
            this.resetStatus({ state: 'showMaskLayer', status: true });
            this.$api.orderApi
                .detail(this.orderId)
                .then(res => {
                    this.orderInformation = res.data;
                    this.pushImage(this.orderInformation.orderPicture);
                    this.resetStatus({ state: 'showMaskLayer', status: false });
                })
                .catch(error => {
                    this.$util.failToast(error.msg);
                });
        },
        ...mapMutations(['simpleAssignment', 'resetStatus'])
    },
    beforeRouteLeave (to, from, next) {
        if (to.name === 'orders' && this.watchPictureModify) {
            this.resetStatus({ state: 'watchPictureModify', status: false });
        }
        next();
    }
};
</script>

<style scoped lang="less" src="./less/update-order.less"></style>
